import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router'
import {HttpRequest} from "../../../../service/httpRequest";
import { NotiService } from "../../../../service/noti.service";

declare let $:any;
@Component({
  selector: 'app-device-info',
  templateUrl: './device-info.component.html',
  styleUrls: ['./device-info.component.css']
})
export class DeviceInfoComponent implements OnInit {

  deviceId:string;
  data:any;
  detailData:any;

  private gizwitsNotiWs:any;
  private eventType = ['device.status.kv','device.status.raw'];

  constructor(private httpRequest:HttpRequest,
              private activeRoute:ActivatedRoute,
              private noti:NotiService) { }

  ngOnInit() {
    this.activeRoute.params.subscribe( params => {
      if(params['deviceId'] == 'none'){
        this.deviceId = '';
      }
      else{
        this.deviceId = params['deviceId'].replace('|','/');
      }
      this.getData();
      this.getDetail();

      if(this.deviceId){
        let p = this.deviceId.split('/');
        this.gizwitsNotiWs = this.noti.init(p[0],[p[1]],this.eventType,this.onEvent);
        this.gizwitsNotiWs.connect();
      }
    });
  }

  getData(){
    this.httpRequest.sendGet('devices',{id:this.deviceId}).subscribe(res=>this.data = res.result,err=>{});
  }
  getDetail(){
    this.httpRequest.sendGet('device/ext/wb',{device_id:this.deviceId}).subscribe(res=>this.detailData = res.result,err=>{});
  }

  pulish(data){
    let p = this.deviceId.split('/');
    let command = "{\"attrs\":{\"cmd\":\""+data+"\"}}";
    this.httpRequest.sendPost('common/sendCommand',{
      product_id:p[0],
      mac:p[1],
      command:command
    }).subscribe(res=>{},err=>{});
  }


  onEvent(msgs){
    let msg = msgs.data;
    for(let key in msg){
      if(key=="run_state_5" && msg[key]=="0"){
        $("."+key).text("限频");
        $("."+key).removeClass("btn-danger");
      }
      if(key=="run_state_5" && msg[key]=="1"){
        $("."+key).text("限频");
        $("."+key).addClass("btn-danger");
      }

      if(key=="run_state_6" && msg[key]=="0"){
        $("."+key).text("锁机");
        $("."+key).removeClass("btn-danger");

      }

      if(key=="run_state_6" && msg[key]=="1"){
        $("."+key).text("锁机");
        $("."+key).addClass("btn-danger");
      }
    }

  }
}
